﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;

namespace Daycare.Services
{
    public class PasswordService
    {
        private static String CreateSalt(int size)
        {
            byte[] buf = new byte[size];
            (new RNGCryptoServiceProvider()).GetBytes(buf);
            return Convert.ToBase64String(buf);
        }

        public static Daycare.Models.Password EncodePassword(string pass, string salt = "")
        {
            if (salt == "")
            {
                salt = PasswordService.CreateSalt(16); 
            }
           
            String saltedPassword = pass + salt;

            byte[] bIn = Encoding.Unicode.GetBytes(saltedPassword);
            byte[] bSalt = Convert.FromBase64String(salt);
            byte[] bAll = new byte[bSalt.Length + bIn.Length];
            byte[] bRet = null;

            Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
            Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);

            HashAlgorithm s = HashAlgorithm.Create("SHA1");
            // Hardcoded "SHA1" instead of Membership.HashAlgorithmType
            bRet = s.ComputeHash(bAll);

            Models.Password pwd = new Models.Password(salt, Convert.ToBase64String(bRet));
            return pwd;
        }
    }
}